package com.jiang.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.jiang.common.constant.AuthServerConstant;
import com.jiang.common.exception.BizCodeEnume;
import com.jiang.common.to.LoginTo;
import com.jiang.common.to.MemberRespEntity;
import com.jiang.common.to.UserRegistTo;
import com.jiang.common.utils.R;
import com.jiang.mall.auth.feign.MemberFeignService;
import com.jiang.mall.auth.feign.ThirdPartFeignService;
import com.jiang.mall.auth.vo.UserLoginVo;
import com.jiang.mall.auth.vo.UserRegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;

//    @GetMapping("/login.html")
//    public String login() {
//        return "login";
//    }
//
//    @GetMapping("/reg.html")
//    public String reg() {
//        return "reg";
//    }

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSms(@RequestParam("phone") String phone) {

        // 60s内同一手机号不能再此发送验证码，即使刷新页面重置页面js的计时器也不行
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            long nowTime = System.currentTimeMillis();
            long subStract = nowTime - l;
            if(subStract < 60000) {
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 4);
        String codeAndTime = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, codeAndTime,10, TimeUnit.MINUTES);
        thirdPartFeignService.sendSms(phone, code);
        return R.ok();
    }

    @PostMapping("/register")
    public String regist(@Valid UserRegisterVo userRegisterVo, BindingResult bindingResult,
            /*区分于model，重定向可以存储值的域*/RedirectAttributes redirectAttributes) {
        if(bindingResult.hasErrors()) {
            Map<String, String> collect = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            model.addAttribute("errors", collect);
            redirectAttributes.addFlashAttribute("errors", collect);
            // Request method Post not support
//            return "reg";
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 校验验证码
        String codeAndTime = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
        if(!StringUtils.isEmpty(codeAndTime)) {
            String code = codeAndTime.split("_")[0];
            if(userRegisterVo.getCode().equals(code)) {
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
                UserRegistTo userRegistTo = new UserRegistTo();
                BeanUtils.copyProperties(userRegisterVo, userRegistTo);
                R r = memberFeignService.register(userRegistTo);
                if(r.getCode() == 0) {
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    HashMap<Object, Object> hashMap = new HashMap<>();
                    hashMap.put("msg", r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors", hashMap);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }
        }else {
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("codeAndTime", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", hashMap);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        LoginTo loginTo = new LoginTo();
        BeanUtils.copyProperties(userLoginVo, loginTo);
        R r = memberFeignService.login(loginTo);
        if(r.getCode() == 0) {
            MemberRespEntity memberRespEntity = r.getData("memberEntity", new TypeReference<MemberRespEntity>() {
            });
            log.info("登陆成功，用户：{}", memberRespEntity);
            session.setAttribute(AuthServerConstant.lOGIN_USER, memberRespEntity);
            return "redirect:http://gulimall.com";
        }else {
            HashMap<Object, Object> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.lOGIN_USER);
        if(attribute == null) {
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }
    }
}
